<?php
declare (strict_types = 1);

namespace app\admin\service;

use app\admin\model\MenuModel;
use app\admin\validate\MenuValidate;
use app\common\libs\helper\TreeHelper;
use think\exception\ValidateException;

class MenuService extends BaseService
{
    /**
     * 获取后台管理员的菜单
     *
     * @Author tanruizheng
     * @DateTime 2021-07-08
     * @param [type] $roleId
     * @return void
     */
    public static function getAdminUserMenuTree($roleId){
        //获取角色的权限菜单
        $menuList = self::getMenuByRole($roleId)['data'];
        $list = [];
        foreach ($menuList as $key => $value) {
            //状态 只列出展示的菜单
            if($value['status'] == MenuModel::STATUS_NO){
                continue;
            }
            if($value['type'] == MenuModel::TYPE_NO_AUTO){
                $value['controller'] .= $value['id'];
                $value['action'] .= $value['id'];
                //链接
                $href = '';
            }else{
                //链接
                $href =  (string)url('/'.$value['app'].'/'.$value['controller'].'/'.$value['action'],['menu_id' => $value['id']],true,true);
            }
            $icon = $value['icon'] ? 'fa '.$value['icon'] : ' ';
            $array = [
                "id"        => $value['id'],
                "pid"       => $value['parentid'],
                'title'     => $value['name'],
                'href'      => $href,
                'icon'      => $icon,
                'target'    => '_self',
            ];
            $list[] = $array;
        }
        $list = TreeHelper::arrayToTree($list, 0, [
            'parentKey' => 'pid',
            'childrenKey' => 'child',
            'maxLevel' => 3 //后台管理界面只支持三层，超出的不层级的不显示
        ]);
        return $list;
    }

    /**
     * 获取角色的权限菜单
     *
     * @Author tanruizheng
     * @DateTime 2021-07-08
     * @param [type] $roleId
     * @return array
     */
    public static function getMenuByRole($roleId){
        $menuList = MenuModel::order('listorder Asc,id ASC')->select()->toArray();
        $result = [];
        foreach ($menuList as $key => $value) {
            $app = $value['app'];//模块
            $controller = $value['controller'];//控制器
            $action = $value['action'];//方法
            if($value['type'] == MenuModel::TYPE_NO_AUTO){
                $controller = $value['controller'].$value['id'];//控制器
                $action = $value['action'].$value['id'];//方法
            }
            //权限验证
            $res = RbacService::auth($roleId,$app,$controller,$action);
            if($res['status']){
                $result[] = $value;
            }
        }
        return self::createSuccess($result);
    }

    /**
     * 获取后台菜单列表
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @return array
     */
    public static function getMenuList(){
        $menuList = MenuModel::select()->toArray();
        $menuList = TreeHelper::arrayToTreeList($menuList, 0, [
            'parentKey' => 'parentid',
        ]);
        return $menuList;
    }

    /**
     * 添加或者编辑菜单
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param [type] $params
     * @return void
     */
    public static function menuAddOrEdit($params){
        try {
            validate(MenuValidate::class)->check($params);
            $data = [
                'name' => $params['name'],
                'app' => $params['app'],
                'controller' => $params['controller'],
                'action' => $params['action'],
                'parentid' => $params['parentid'],
                'parameter' => $params['parameter'],
                'type' => $params['type'],
                'status' => $params['status'],
                'remark' => $params['remark'] ?? '',
                'listorder' => $params['listorder'] ?? 0,
                'icon' => $params['icon'] ?? '',
            ];
            if(isset($params['id']) && $params['id']){
                $res = MenuModel::where('id',$params['id'])->save($data);
            }else{
                $res = MenuModel::create($data);
            }
            if($res !== false){
                return self::createSuccess('保存成功');
            }
            return self::createFail('保存失败');
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::createFail($e->getError());
        }
    }

    /**
     * 删除菜单
     *
     * @Author tanruizheng
     * @DateTime 2021-07-09
     * @param [type] $id
     * @return void
     */
    public static function menuDelete($id){
        if(!$id) return self::createFail('参数错误!');
        $menuInfo = MenuModel::where('id',$id)->findOrEmpty();
        if(empty($menuInfo)){
            return self::createFail('菜单信息错误!');
        }
        $count = MenuModel::where('parentid',$id)->count();
        if($count){
            return self::createFail('该菜单还有子级菜单,不能删除!');
        }
        $res = $menuInfo->delete();
        if($res !== false){
            return self::createSuccess('删除成功!');
        }
        return self::createFail('删除失败!');
    }
}
